using System;
using System.IO;
using System.Text;

namespace Game.Network {
    public class PacketWriter {
        private MemoryStream m_stream;
        private byte[] m_buffer;

        public PacketWriter (byte[] buffer) {
            m_stream = new MemoryStream (buffer);
            m_buffer = new byte[4];
        }

        public PacketWriter (int capacity) {
            byte[] buffer = new byte[capacity];
            m_stream = new MemoryStream (buffer);
            m_buffer = new byte[4];
        }

        public void Write (bool value) {
            m_stream.WriteByte ((byte)(value ? 1 : 0));
        }

        public void Write (byte value) {
            m_stream.WriteByte (value);
        }

        public void Write (sbyte value) {
            m_stream.WriteByte ((byte)value);
        }

        public void Write (short value) {
            m_buffer [0] = (byte)(value >> 8);
            m_buffer [1] = (byte)value;

            m_stream.Write (m_buffer, 0, 2);
        }

        public void Write (int value) {
            m_buffer [0] = (byte)(value >> 24);
            m_buffer [1] = (byte)(value >> 16);
            m_buffer [2] = (byte)(value >> 8);
            m_buffer [3] = (byte)(value);

            m_stream.Write (m_buffer, 0, 4);
        }

        public void Write (uint value) {
            m_buffer [0] = (byte)(value >> 24);
            m_buffer [1] = (byte)(value >> 16);
            m_buffer [2] = (byte)(value >> 8);
            m_buffer [3] = (byte)(value);
            
            m_stream.Write (m_buffer, 0, 4);
        }

        public void Write (byte[] value, int offset, int size) {
            m_stream.Write (value, offset, size);
        }

        public void WriteAsciiPString (string value) {
            int length = value.Length;
            Write ((byte)length);
            Encoding.ASCII.GetBytes (value, 0, length, m_stream.GetBuffer (), (int)m_stream.Position);
            m_stream.Position += length;
        }

        public void WriteAsciiRawString (string value) {
            int length = value.Length;
            Encoding.ASCII.GetBytes (value, 0, length, m_stream.GetBuffer (), (int)m_stream.Position);
            m_stream.Position += length;
        }

        public long Length{ get { return m_stream.Length; } }

        public long Position{ get { return m_stream.Position; } }

        public long Seek (long offset, SeekOrigin origin) {
            return m_stream.Seek (offset, origin);
        }

        public byte[] ToArray () {
            return m_stream.ToArray ();
        }
    }
}

